package org.daochong.spring;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.daochong.lang.Resource;
import org.daochong.lang.SystemLogger;
import org.daochong.spring.util.ResourceAdaper;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class SpringMVCLoader implements ApplicationListener<ContextRefreshedEvent> {

	public static String DEFAULT_PATH = "/ext/spring/**/springmvc*.xml";

	private Set<String> rs = new LinkedHashSet<String>();

	public void onApplicationEvent(ContextRefreshedEvent event) {
		ConfigurableApplicationContext context = (ConfigurableApplicationContext) event.getApplicationContext();
		if (context.getParent() == null)
			return;
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(
				(BeanDefinitionRegistry) context.getBeanFactory());
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(context));
		List<Resource> list = Resource.getResources(DEFAULT_PATH);
		if (list != null && list.size() > 0) {
			for (org.daochong.lang.Resource resource : list) {
				if (rs.contains(resource.getContextPath())) {
					SystemLogger.info("SpringMVCExt", "Ignore file " + resource.getSource());
					continue;
				} else {
					rs.add(resource.getContextPath());
					beanDefinitionReader.loadBeanDefinitions(new ResourceAdaper(resource));
				}
			}
		}
	}

}
